package com.ruoyi.jiaopei.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.jiaopei.domain.TbCurriculum;
import com.ruoyi.jiaopei.domain.TbStudent;
import com.ruoyi.jiaopei.domain.vo.StudentCurriculumVo;
import com.ruoyi.jiaopei.domain.vo.TbCurriculumVo;
import com.ruoyi.jiaopei.mapper.TbCurriculumMapper;
import com.ruoyi.jiaopei.mapper.TbStudentMapper;
import com.ruoyi.jiaopei.service.ITbStudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.jiaopei.domain.bo.TbCurriculumStudentBo;
import com.ruoyi.jiaopei.domain.vo.TbCurriculumStudentVo;
import com.ruoyi.jiaopei.domain.TbCurriculumStudent;
import com.ruoyi.jiaopei.mapper.TbCurriculumStudentMapper;
import com.ruoyi.jiaopei.service.ITbCurriculumStudentService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 课程学员Service业务层处理
 *
 * @author macy
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class TbCurriculumStudentServiceImpl implements ITbCurriculumStudentService {

    private final TbCurriculumStudentMapper baseMapper;
    private final TbCurriculumMapper curriculumMapper;
    private final TbStudentMapper studentMapper;

    /**
     * 查询课程学员
     */
    @Override
    public TbCurriculumStudentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }


    @Override
    public Long selectCount(Wrapper<TbCurriculumStudent> queryWrapper) {
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 查询课程学员列表
     */
    @Override
    public TableDataInfo<TbCurriculumStudentVo> queryPageList(TbCurriculumStudentBo bo, PageQuery pageQuery) {
        QueryWrapper<TbCurriculumStudent> lqw = buildQueryWrapper2(bo);
        Page<TbCurriculumStudentVo> result = baseMapper.selectPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private QueryWrapper<TbCurriculumStudent> buildQueryWrapper2(TbCurriculumStudentBo bo) {
        QueryWrapper<TbCurriculumStudent> lqw = Wrappers.query();
        lqw.eq(bo.getStudentId() != null, "t.student_id", bo.getStudentId());
        lqw.eq(bo.getSource() != null, "t.source", bo.getSource());
        lqw.eq(bo.getCurriculumId() != null, "t.curriculum_id", bo.getCurriculumId());
        lqw.like(StringUtils.isNotBlank(bo.getCurriculumName()), "t.curriculum_name", bo.getCurriculumName());
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), "u.name", bo.getStudentName());
        lqw.like(StringUtils.isNotBlank(bo.getSalesName()), "u1.nick_name", bo.getSalesName());

        lqw.like(StringUtils.isNotBlank(bo.getSource()), "t.source", bo.getSource());
        lqw.like(StringUtils.isNotBlank(bo.getPaymentStatus()), "t.payment_status", bo.getPaymentStatus());


        lqw.orderByDesc("created_date");

        return lqw;
    }


    /**
     * 查询课程学员列表
     */
    @Override
    public List<TbCurriculumStudentVo> queryList(TbCurriculumStudentBo bo) {
        LambdaQueryWrapper<TbCurriculumStudent> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbCurriculumStudent> buildQueryWrapper(TbCurriculumStudentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbCurriculumStudent> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStudentId() != null, TbCurriculumStudent::getStudentId, bo.getStudentId());
        lqw.eq(bo.getCurriculumId() != null, TbCurriculumStudent::getCurriculumId, bo.getCurriculumId());
        lqw.eq(bo.getSource() != null, TbCurriculumStudent::getSource, bo.getSource());
        lqw.eq(StrUtil.isNotBlank(bo.getPaymentStatus()), TbCurriculumStudent::getPaymentStatus, bo.getPaymentStatus());

        lqw.like(StringUtils.isNotBlank(bo.getCurriculumName()), TbCurriculumStudent::getCurriculumName, bo.getCurriculumName());
        return lqw;
    }


    /**
     * 新增课程学员
     */
    @Override
    public Boolean insertByBo(TbCurriculumStudentBo bo) {
        TbCurriculumStudent add = BeanUtil.toBean(bo, TbCurriculumStudent.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改课程学员
     */
    @Override
    public Boolean updateByBo(TbCurriculumStudentBo bo) {
        TbCurriculumStudent update = BeanUtil.toBean(bo, TbCurriculumStudent.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbCurriculumStudent entity){
        if(null==entity.getId()){
            if(null==entity.getCreatedDate()){
                entity.setCreatedDate(new Date());
            }
            if(null==entity.getPaymentDate()){
                entity.setPaymentDate(new Date());
            }
            if(StrUtil.isBlank(entity.getPaymentStatus())){
                throw new ServiceException("付款状态不能为空");
            }
            if(null==entity.getCurriculumId()){
                throw new ServiceException("课程名称不能为空");
            }
            if(null==entity.getLessonHours()||entity.getLessonHours().doubleValue()<=0){
                throw new ServiceException("课时不能为空");
            }
            if(null==entity.getPrice()){
                throw new ServiceException("价格不能为空");
            }

            TbCurriculumVo vo=curriculumMapper.selectVoOne(new LambdaQueryWrapper<TbCurriculum>()
                .eq(TbCurriculum::getId,entity.getCurriculumId())
            );
            if(null!=vo){
                entity.setCurriculumName(vo.getName());
                entity.setPrice(vo.getPrice());
                if(null==entity.getLessonHours()){
                    entity.setLessonHours(vo.getLessonHours());
                }
                entity.setSurplus(entity.getLessonHours());
            }
        }else{
            TbCurriculumStudentVo vo=baseMapper.selectVoById(entity.getId());
            if(null==vo){
                throw new ServiceException("修改的信息不存在");
            }
            if(!vo.getCurriculumId().equals(entity.getCurriculumId())){
                throw new ServiceException("不能修改课程信息");
            }
            /**
             * 查找 学员 课时余额
             */
            QueryWrapper<TbStudent> lqw1 = Wrappers.query();
            lqw1.eq(null!=entity.getStudentId(),"a.student_id",entity.getStudentId());
            lqw1.eq(null!=entity.getCurriculumId(),"a.curriculum_id",entity.getCurriculumId());

            StudentCurriculumVo studentCurriculumVo=studentMapper.queryStudentCurriculumInfo(lqw1.lambda());
            if(null!=studentCurriculumVo){
                if(entity.getLessonHours().longValue()<studentCurriculumVo.getYyHours().longValue()){
                    throw new ServiceException("修改课时不能小于核销总课时");
                }
            }else{
                if(entity.getLessonHours().longValue()<vo.getLessonHours().longValue()){
                    throw new ServiceException("修改课时不能小于原课时");
                }
            }
        }
    }

    /**
     * 批量删除课程学员
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
